package cn.edu.ncu.housinghub.interceptor;



import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.constant.SystemConstant;
import cn.edu.ncu.housinghub.entity.user.User;
import cn.edu.ncu.housinghub.exception.BusinessException;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Set;

@Component
public class LandlordRoleInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 定义需要拦截的URL模式（房东专属操作）
        String requestURI = request.getRequestURI();

        // 判断是否需要进行房东角色校验
        if (needLandlordRole(requestURI)) {
            // 2. 获取请求头中的token
            String token = request.getHeader("info");

            // 3. 验证token是否存在
            if (token == null || token.trim().isEmpty()) {
                throw new BusinessException(ErrorCodeConstant.TOKEN_MISSING);
            }

            // 4. 从Redis中查询token对应的用户信息
            Set<String> keys = redisTemplate.keys(SystemConstant.REDIS_TOKEN_PREFIX_USER.getStringValue() + "*:" + token);
            if (keys == null || keys.isEmpty()) {
                throw new BusinessException(ErrorCodeConstant.TOKEN_INVALID);
            }

            // 5. 获取用户信息
            String redisKey = keys.iterator().next();
            User loginUser = (User) redisTemplate.opsForValue().get(redisKey);
            if (loginUser == null) {
                throw new BusinessException(ErrorCodeConstant.TOKEN_INVALID);
            }

            // 6. 验证用户角色是否为房东或普通用户（普通用户可以发布房源成为房东）
            if (loginUser.getRole() != SystemConstant.ROLE_LANDLORD.getIntegerValue() &&
                loginUser.getRole() != SystemConstant.ROLE_TENANT.getIntegerValue()) {
                throw new BusinessException(ErrorCodeConstant.USER_AUTH_ERROR);
            }
        }

        // 验证通过，继续处理请求
        return true;
    }



    /**
     * 判断当前请求是否需要房东角色
     */
    private boolean needLandlordRole(String requestURI) {
        // 配置需要房东角色才能访问的子URL模式

        return requestURI.startsWith("/landlord/publish");
    }
}
